package com.ly.pic.controller;

import com.ly.pic.model.Result;
import com.ly.pic.service.FeatureExtractionAGG19Service;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;



@RestController
@RequestMapping("/api/feature")
public class FeatureController {

    @Autowired
    private FeatureExtractionAGG19Service featureExtractionAGG19Service;


    @PostMapping("/search19")
    public Result search19(@RequestParam("file") MultipartFile file, @RequestParam("similarity") Double similarity) throws Exception {
        try (InputStream inputStream = file.getInputStream()) {
            INDArray indArray = featureExtractionAGG19Service.extractFeatures(inputStream);
            boolean b = featureExtractionAGG19Service.comparativeFeatureVector(indArray, similarity);
            return new Result(b);
        }
    }

    @PostMapping("/uploadImage19")
    public Result uploadImage19(@RequestParam("file") MultipartFile file) throws Exception {
        try (InputStream inputStream = file.getInputStream()) {
            // 将 InputStream 转换为 ByteArrayInputStream 以便重复读取
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }

            byte[] bytes = byteArrayOutputStream.toByteArray();
            ByteArrayInputStream byteArrayInputStream1 = new ByteArrayInputStream(bytes);
            ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(bytes);

            try {
                // 保存图片
                saveImage(byteArrayInputStream1);

                // 提取特征
                INDArray indArray = featureExtractionAGG19Service.extractFeatures(byteArrayInputStream2);

                // 添加特征
                if (featureExtractionAGG19Service.addFeatures(indArray)) {
                    return new Result(true);
                } else {
                    return new Result(false, "上传同一张图片或添加失败", 1);
                }

                //将图片写入向量特征JSON文件
            } finally {
                byteArrayInputStream1.close();
                byteArrayInputStream2.close();
            }
        }
    }

    public static void saveImage(InputStream inputStream) throws IOException {
        // 获取当前时间并格式化为纳秒级别的时间戳
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSnnn"));

        File fileModel = new File("images/" + timestamp+".png");
        if (!fileModel.getParentFile().exists()) {
            fileModel.getParentFile().mkdirs();
        }

        BufferedImage image = ImageIO.read(inputStream);
        if (image == null) {
            throw new IOException("Failed to read image from InputStream");
        }
        ImageIO.write(image, "png", fileModel);
    }



}
